package com.teach.demo02;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

public class TCPServer {

	private static final int PORT = 1001;

	public static void main(String[] args) throws Exception {
		ServerSocket serverSocket = null;
		try {

			serverSocket = new ServerSocket(PORT);// 绑定服务所有IP的端口
			// 服务器创建完成
			System.out.println("服务器创建完成[" + serverSocket.getInetAddress().getHostAddress() + ":"
					+ serverSocket.getLocalPort() + "]");

			while (true) {
				Socket client = serverSocket.accept();
				
				String clientInfo = String.format("客户端[%s:%s]", client.getInetAddress().getHostAddress(), client.getPort())
;				
				//接受客戶端的发生的文字
				Thread t1 = new Thread(()->{
					try {
						InputStream in =  client.getInputStream();
						DataInputStream din = new DataInputStream(in);
						String msg = null;
						while(true) {
							msg = din.readUTF();
							System.out.println("接收了"+clientInfo+"的消息："+msg);
						}
					}catch (Exception e) {
//						System.out.println(clientInfo+"接收消息异常");
//						e.printStackTrace();
						System.out.println("关闭"+clientInfo);
						try {
							client.close();
						} catch (IOException e1) {
						}// 关闭客户端
					}
				});
				t1.start();
				

//				System.out.println("关闭"+clientInfo);
//				client.close();// 关闭客户端

			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			serverSocket.close();// 关闭服务器端
		}
	}
}
